<?php
class ChangeUsernameLog extends DataObject {
    private static $singular_name = "Change Username Log";
    private static $plural_name = "Change Username Logs";
    
    private static $db = array(
        'FromUsername' => 'Varchar',
        'ToUsername' => 'Varchar'
    );

    private static $has_one = array(
    	'UpdateBy' => 'Member',
    	'Member' => 'Member'
	);

    private static $searchable_fields = array(
        'FromUsername',
        'ToUsername',
        'Member.Username'
    );

    private static $summary_fields = array(
        'Created',
        'Member.Username',
        'Member.Name',
        'FromUsername',
        'ToUsername',
        'UpdateBy.Username'
    );
	
	/**
     * @return array
     */
    function fieldLabels($includerelations = true) {
        $labels = parent::fieldLabels($includerelations);

		$labels['Member.Username'] = _t('ChangeUsernameLog.MEMBER_USERNAME', 'Member Username');
		$labels['Member.Name'] = _t('ChangeUsernameLog.MEMBER_NAME', 'Member Name');
        $labels['FromUsername'] = _t('ChangeUsernameLog.FROM_USERNAME', 'From Username');
        $labels['ToUsername'] = _t('ChangeUsernameLog.TO_USERNAME', 'To Username');
        $labels['Created'] = _t('ChangeUsernameLog.DATE', 'Date');
		$labels['UpdateBy.Username'] = _t('ChangeUsernameLog.UPDATED_BY', 'Updated By');
		
		return $labels;
    }

    function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->replaceField('FromUsername', UsernameField::create('FromUsername', $this->fieldLabel('FromUsername')));
        $fields->replaceField('ToUsername', UniqueUsernameField::create('ToUsername', $this->fieldLabel('ToUsername')));
		if(!$this->exists()){
			$fields->removeByName('MemberID');
			$fields->removeByName('UpdateByID');
		}

        return $fields;
    }

    function onBeforeWrite() {
        parent::onBeforeWrite();

        if(!$this->MemberID) {
            $this->MemberID = Distributor::get_id_by_username($this->FromUsername);
        }
		
		if(!$this->exists()){
			$this->UpdateByID = Member::currentUserID();
		}
    }

    function canEdit($member = null) {
        return false;
    }

    function canDelete($member = null) {
        return false;
    }

}
?>